package com.zrzhen.springbootdemo.common.http.asyncHttp;

import com.zrzhen.springbootdemo.common.http.Ipphttp;
import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.Dsl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

@Component
public class AsyncHttp implements Ipphttp {

    private static final Logger logger = LoggerFactory.getLogger(AsyncHttp.class);

    private volatile static AsyncHttpClient client;

    public static AsyncHttpClient getClient() {
        if (client == null) {
            synchronized (AsyncHttpClient.class) {
                if (client == null) {
                    client = Dsl.asyncHttpClient(
                            Dsl.config().setUseNativeTransport(System.getProperty("os.name").toLowerCase().indexOf("linux") > 0));
                }
            }
        }
        return client;
    }

    @Override
    public String get(String url, Map<String, String> params, Map<String, String> headers) {
        String respstr = null;
//        BoundRequestBuilder boundGetRequest = getClient().prepareGet(url);
//        Future<Response> responseFuture = boundGetRequest.execute();
//        try {
//            respstr=responseFuture.get().getResponseBody();
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        } catch (ExecutionException e) {
//            e.printStackTrace();
//        }

        Future<String> whenStatusCode = getClient().prepareGet(url).execute(new ApiAsyncCompletionHandler());

        try {
            respstr = whenStatusCode.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return respstr;
    }

    @Override
    public String postJson(String url, String jsonParams, Map<String, String> headers) {
        return null;
    }

    @Override
    public String postJsonMap(String url, Map<String, Object> params, Map<String, String> headers) {
        return null;
    }

    @Override
    public String postForm(String url, Map<String, String> params, Map<String, String> headers) {
        return null;
    }

    @Override
    public String postXmlParams(String url, String xml, Map<String, String> headers) {
        return null;
    }

    @Override
    public String postFile(String url, File file, Map<String, String> headers) {
        return null;
    }
}
